// 干预计划页面
const auth = require('../../utils/auth.js');
const moment = require('../../utils/moment');

Page({
  data: {
    // 当前计划
    currentPlan: null,
    
    // 计划列表
    plans: [],
    
    // 今日任务
    todayTasks: [],
    
    // 完成情况统计
    statistics: {
      totalDays: 0,
      completedDays: 0,
      completionRate: 0,
      currentStreak: 0,
      longestStreak: 0
    },
    
    // 页面状态
    loading: false,
    error: null,
    
    // 日历相关
    calendarData: [],
    selectedDate: '',
    currentMonth: '',
    
    // 任务类型配置
    taskTypes: [
      {
        id: 'acupoint',
        name: '耳穴压丸',
        icon: '👂',
        description: '按摩耳部穴位，每次5-10分钟',
        frequency: '每日2次',
        color: '#4A90E2'
      },
      {
        id: 'eye_exercise',
        name: '眼保健操',
        icon: '👀',
        description: '标准眼保健操，放松眼部肌肉',
        frequency: '每日3次',
        color: '#50C878'
      },
      {
        id: 'outdoor',
        name: '户外活动',
        icon: '🌞',
        description: '户外自然光照，增强眼部健康',
        frequency: '每日1小时',
        color: '#FFA500'
      },
      {
        id: 'rest',
        name: '用眼休息',
        icon: '😌',
        description: '20-20-20法则，保护视力',
        frequency: '每小时1次',
        color: '#9370DB'
      }
    ]
  },

  /**
   * 页面加载
   */
  onLoad() {
    this.initPage();
  },

  /**
   * 页面显示
   */
  onShow() {
    this.refreshData();
  },

  /**
   * 初始化页面
   */
  async initPage() {
    try {
      this.setData({ loading: true });
      
      // 检查登录状态
      if (!auth.getToken()) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 设置当前日期
      const today = new Date();
      const selectedDate = moment(today).format('YYYY-MM-DD');
      const currentMonth = moment(today).format('YYYY-MM');
      
      this.setData({
        selectedDate,
        currentMonth
      });
      
      // 加载数据
      await this.loadCurrentPlan();
      await this.loadTodayTasks();
      await this.loadStatistics();
      await this.loadCalendarData();
      
      this.setData({ loading: false });
      
    } catch (error) {
      console.error('页面初始化失败:', error);
      this.setData({
        loading: false,
        error: error.message || '页面加载失败'
      });
    }
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    try {
      await this.loadTodayTasks();
      await this.loadStatistics();
    } catch (error) {
      console.error('刷新数据失败:', error);
    }
  },

  /**
   * 加载当前计划
   */
  async loadCurrentPlan() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${getApp().globalData.apiBaseUrl}/intervention/plans/current`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${auth.getToken()}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            this.setData({
              currentPlan: res.data.data
            });
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '获取当前计划失败'));
          }
        },
        fail: (error) => {
          reject(new Error('网络请求失败'));
        }
      });
    });
  },

  /**
   * 加载今日任务
   */
  async loadTodayTasks() {
    return new Promise((resolve, reject) => {
      const today = moment(new Date()).format('YYYY-MM-DD');
      
      wx.request({
        url: `${getApp().globalData.apiBaseUrl}/intervention/tasks`,
        method: 'GET',
        data: {
          date: today
        },
        header: {
          'Authorization': `Bearer ${auth.getToken()}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            this.setData({
              todayTasks: res.data.data || []
            });
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '获取今日任务失败'));
          }
        },
        fail: (error) => {
          reject(new Error('网络请求失败'));
        }
      });
    });
  },

  /**
   * 加载统计信息
   */
  async loadStatistics() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${getApp().globalData.apiBaseUrl}/intervention/statistics`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${auth.getToken()}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            this.setData({
              statistics: res.data.data || this.data.statistics
            });
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '获取统计信息失败'));
          }
        },
        fail: (error) => {
          reject(new Error('网络请求失败'));
        }
      });
    });
  },

  /**
   * 加载日历数据
   */
  async loadCalendarData() {
    return new Promise((resolve, reject) => {
      const startDate = moment(new Date(this.data.currentMonth + '-01')).format('YYYY-MM-DD');
      const endDate = moment(new Date(this.data.currentMonth + '-01')).format('YYYY-MM-DD');
      
      wx.request({
        url: `${getApp().globalData.apiBaseUrl}/intervention/calendar`,
        method: 'GET',
        data: {
          start_date: startDate,
          end_date: endDate
        },
        header: {
          'Authorization': `Bearer ${auth.getToken()}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            this.setData({
              calendarData: res.data.data || []
            });
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '获取日历数据失败'));
          }
        },
        fail: (error) => {
          reject(new Error('网络请求失败'));
        }
      });
    });
  },

  /**
   * 标记任务完成
   */
  async markTaskCompleted(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const taskIndex = e.currentTarget.dataset.index;
    
    try {
      wx.showLoading({ title: '更新中...' });
      
      await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/intervention/tasks/${taskId}/complete`,
          method: 'POST',
          data: {
            completion_time: new Date().toISOString()
          },
          header: {
            'Authorization': `Bearer ${auth.getToken()}`
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data.success) {
              resolve(res.data);
            } else {
              reject(new Error(res.data.message || '标记失败'));
            }
          },
          fail: (error) => {
            reject(new Error('网络请求失败'));
          }
        });
      });
      
      // 更新本地数据
      const tasks = this.data.todayTasks;
      tasks[taskIndex].completed = true;
      tasks[taskIndex].completion_time = new Date().toISOString();
      
      this.setData({
        todayTasks: tasks
      });
      
      // 刷新统计数据
      await this.loadStatistics();
      
      wx.hideLoading();
      wx.showToast({
        title: '任务已完成',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'error'
      });
    }
  },

  /**
   * 创建新计划
   */
  createNewPlan() {
    wx.navigateTo({
      url: '/pages/intervention/plan-create/plan-create'
    });
  },

  /**
   * 查看计划详情
   */
  viewPlanDetail() {
    if (!this.data.currentPlan) {
      wx.showToast({
        title: '暂无活动计划',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/intervention/plan-detail/plan-detail?id=${this.data.currentPlan.id}`
    });
  },

  /**
   * 查看历史记录
   */
  viewHistory() {
    wx.navigateTo({
      url: '/pages/intervention/history/history'
    });
  },

  /**
   * 日期选择
   */
  onDateSelect(e) {
    const date = e.currentTarget.dataset.date;
    this.setData({
      selectedDate: date
    });
    
    // 加载选中日期的任务
    this.loadTasksByDate(date);
  },

  /**
   * 加载指定日期的任务
   */
  async loadTasksByDate(date) {
    try {
      wx.showLoading({ title: '加载中...' });
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/intervention/tasks`,
          method: 'GET',
          data: { date },
          header: {
            'Authorization': `Bearer ${auth.getToken()}`
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (res.statusCode === 200 && res.data.success) {
        this.setData({
          todayTasks: res.data.data || []
        });
      }
      
      wx.hideLoading();
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 分享功能
   */
  onShareAppMessage() {
    return {
      title: '我在坚持护眼计划，一起来保护视力吧！',
      path: '/pages/intervention/plan/plan',
      imageUrl: '/images/share-plan.png'
    };
  }
});
